package com.easy.concert.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easy.common.bean.ConcertBean;
import com.easy.common.bean.SeatBean;
import com.easy.common.bean.VenueBean;
import com.easy.common.service.IConcertService;
import com.easy.common.service.ISeatService;
import com.easy.common.service.IVenueService;
import com.easy.concert.mapper.ConcertMapper;
import com.easy.concert.repository.ConcertRepository;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.easy.common.util.SYS;
import com.easy.common.exception.ServiceException;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@DubboService // dubbo服务
public class ConcertServiceImpl extends
        ServiceImpl<ConcertMapper, ConcertBean> implements IConcertService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @DubboReference
    private ISeatService seatService;
    @DubboReference
    private IVenueService venueService;

    @Autowired
    private ConcertRepository concertRepository;


    @Override
    public ConcertBean getConcertById(Integer id) {
        return super.getById(id);
    }

    @Override
    public ConcertBean getConcertByTitle(String title) {
        LambdaQueryWrapper<ConcertBean> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ConcertBean::getTitle,title);
        return super.getOne(queryWrapper);
    }
    @Override
    public IPage<ConcertBean> getPageByVenueId(Integer venueId, IPage<ConcertBean> page) {
        LambdaQueryWrapper<ConcertBean> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ConcertBean::getVenueid, venueId)
                .eq(ConcertBean::getIsdel, 0);
        return super.page(page, queryWrapper);
    }

    @Override
    public Integer addConcert(ConcertBean concertBean) {
        if(super.save(concertBean))
            return 1;
        else
            return 0;
    }

    @Override
    public Integer updateConcert(ConcertBean concertBean) {
        return super.updateById(concertBean)?1:0;
    }

    @Override
    public Integer deleteConcert(Integer id) {
        return super.removeById(id)?1:0;
    }

    @Override
    public Integer revertConcert(Integer id) {
        ConcertBean concertBean = super.getById(id);
        if(concertBean!=null){
            concertBean.setStatus(concertBean.getStatus() == 1?0:1);
            return super.updateById(concertBean)?1:0;
        }
        return 0;
    }

    @Override
    public List<ConcertBean> getAll(ConcertBean concertBean) {
        LambdaQueryWrapper<ConcertBean> queryWrapper = new LambdaQueryWrapper<>();
        return super.list(queryWrapper);
    }

    @Override
    public ConcertBean getConcertWithVenue(Integer id) {
        // 调用自定义的联表查询方法
        return baseMapper.selectConcertWithVenue(id);
    }
    //查询场地信息
    @Override
    public IPage<ConcertBean> getPageWithVenue(Page<ConcertBean> page) {
        IPage<ConcertBean> ipage = super.page(page,new QueryWrapper<ConcertBean>());
        ipage.getRecords().forEach(concert -> {
            VenueBean venue = venueService.getVenueById(concert.getVenueid());
            concert.setVenueName(venue.getName());
        });
        return ipage;
    }

    @Override
public Page<ConcertBean> listByMultiCondition(String keyword, String city, Long startDate, Long endDate, Long current, Long size) {
    // 使用 QueryWrapper 手动构造联表查询条件
    QueryWrapper<ConcertBean> queryWrapper = new QueryWrapper<>();

    // 城市模糊查询（关联 venue 表的 address 字段，需要根据实际表结构调整字段名）
    if (StringUtils.isNotBlank(city)) {
        // 修复：使用正确的字段名，根据实际数据库结构调整
        queryWrapper.apply("EXISTS (SELECT 1 FROM venue v WHERE v.id = concert.venueid AND v.address LIKE CONCAT('%', {0}, '%'))", city);
    }

    // 时间范围查询（演唱会 startdate）
    if (startDate != null && endDate != null) {
        queryWrapper.between("startdate", new java.util.Date(startDate), new java.util.Date(endDate));
    }

    // 关键词模糊查询（标题/艺人）
    if (StringUtils.isNotBlank(keyword)) {
        queryWrapper.and(wrapper -> wrapper.like("title", keyword).or().like("artist", keyword));
    }

    // 分页查询
    Page<ConcertBean> page = new Page<>(current, size);
    return (Page<ConcertBean>) super.page(page, queryWrapper);
}
//???????????????????????????????????????????????????????????????????????????????????????????????????????
    @Override
    public List<ConcertBean> searchConcert(String keyword) {
        return concertRepository.searchByKeyword(keyword);
    }

    @Override
    public List<ConcertBean> getRecommendConcert() {
        return concertRepository.findRecommended();
    }


    //    @Override
//    public IPage<ConcertBean> getPage(ConcertBean concertBean,IPage<ConcertBean> page) {
//        LambdaQueryWrapper<ConcertBean> queryWrapper = new LambdaQueryWrapper<>();
//        if(concertBean!=null && concertBean.getId()!=null && concertBean.getId().describeConstable().isEmpty()){
//            queryWrapper.like(ConcertBean::getId,concertBean.getId());
//        }
//        return super.page(page,queryWrapper);
//    }
@Override
public IPage<ConcertBean> getPage(ConcertBean concertBean, IPage<ConcertBean> page) {
    LambdaQueryWrapper<ConcertBean> queryWrapper = new LambdaQueryWrapper<>();
//    // ID模糊查询
//    if (concertBean != null && concertBean.getId() != null && !concertBean.getId().toString().trim().isEmpty()) {
//        queryWrapper.like(ConcertBean::getId, concertBean.getId());
//    }
    // 演唱会标题模糊查询
    if (concertBean != null && concertBean.getTitle() != null && !concertBean.getTitle().trim().isEmpty()) {
        queryWrapper.like(ConcertBean::getTitle, concertBean.getTitle());
    }
    // 艺人名称模糊查询
    if (concertBean != null && concertBean.getArtist() != null && !concertBean.getArtist().trim().isEmpty()) {
        queryWrapper.like(ConcertBean::getArtist, concertBean.getArtist());
    }
    page.setTotal(super.count(queryWrapper));
    return super.page(page, queryWrapper);
}

    // 预热
    @Override
    public Boolean startPrehead(Integer id) {
        //参数id  演唱会id
        //redis中是否有演唱会信息。如果有，则已经开始
        String Concert_redis_key=SYS.SK_PRE_CONCERT_KEY+id;
        if(redisTemplate.hasKey(Concert_redis_key)){
            throw new ServiceException("活动已经预热");
        }
        //获取数据库中的活动信息
        ConcertBean concertBean = this.getById(id);
        if(concertBean==null){
            throw new ServiceException("活动不存在");
        }
        if(concertBean.getStatus()!=0 && concertBean.getStatus()!=1 && concertBean.getStatus()!=2){
            throw new ServiceException("活动异常");
        }
        //活动结束时间毫秒数
        LocalDateTime endTime = concertBean.getEnddate();
        Long endTimeMillis = endTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();

        //活动开始时间毫秒数
        LocalDateTime startTime = concertBean.getStartdate();
        Long startTimeMillis = startTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();

        //当前时间毫秒数
        Long currentTimeMillis = System.currentTimeMillis();
        //缓存的有效时间   时间片段：活动开始时间-当前时间
        Long expireTime = endTimeMillis - currentTimeMillis;
        if(currentTimeMillis > endTimeMillis){
            throw new ServiceException("活动已结束");
        }

        //开始预热操作
        //1.将抢票信息保存到redis中
        Map concertMap = new HashMap();
        //抢票状态
        concertMap.put(SYS.SK_CONCERT_STATUS_HASH_KEY,1);
        //抢票开始时间
        concertMap.put(SYS.SK_CONCERT_STATUS_TIME_KEY,startTimeMillis);
        //抢票结束时间
        concertMap.put(SYS.SK_CONCERT_END_TIME_KEY,endTimeMillis);
        //保存到redis中
        redisTemplate.opsForHash().putAll(Concert_redis_key,concertMap);
        redisTemplate.expire(Concert_redis_key,expireTime, TimeUnit.MILLISECONDS);


        //2.将座位信息保存到redis中
        //获取所有座位信息
        QueryWrapper<SeatBean> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SeatBean::getConcertid,id);
        List<SeatBean> seatBeanList = seatService.list(queryWrapper);
        for(SeatBean seatBean:seatBeanList){
            String seat_redis_key = SYS.SK_PRE_SEAT_KEY+seatBean.getId();
            int sk_stock = seatBean.getCount();
            redisTemplate.opsForValue().set(seat_redis_key,sk_stock,expireTime,TimeUnit.MILLISECONDS);
        }

        //修改数据中抢票的状态
        concertBean.setStatus(1);//?????????????????????????????????????????????????????????????????????
        this.updateById(concertBean);

        return true;
    }









}





























